/**
* @program: src
*
* @description:
*
* @author: Mr.chen
*
* @create: 2022-04-13 11:50
**/
package prometheus

import (
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
	"do_demo/srv/common/core/metric"
	"do_demo/srv/common/core/prometheus"
	"do_demo/srv/common/core/timex"
)

const serverNamespace = "http_server"

var (
	metricServerReqDur = metric.NewHistogramVec(&metric.HistogramVecOpts{
		Namespace: serverNamespace,
		Subsystem: "requests",
		Name:      "duration_ms",
		Help:      "http server requests duration(ms).",
		Labels:    []string{"path"},
		Buckets:   []float64{5, 10, 25, 50, 100, 250, 500, 1000},
	})

	metricServerReqCodeTotal = metric.NewCounterVec(&metric.CounterVecOpts{
		Namespace: serverNamespace,
		Subsystem: "requests",
		Name:      "code_total",
		Help:      "http server requests error count.",
		Labels:    []string{"path", "code"},
	})
)
// PrometheusHandler returns a middleware that reports stats to prometheus.
func PrometheusHandler()  gin.HandlerFunc {
	return func(c *gin.Context) {
		if !prometheus.Enabled() {
			c.Next()
			return
		}
		startTime := timex.Now()
		path := c.Request.URL.Path
		//cw := &response.WithCodeResponseWriter{Writer: w}
		defer func() {
			metricServerReqDur.Observe(int64(timex.Since(startTime)/time.Millisecond), path)
			metricServerReqCodeTotal.Inc(path, strconv.Itoa(c.Writer.Status()))
		}()
		//next.ServeHTTP(cw, r)
		// 处理请求
		c.Next()

	}
}


